#include "ML_SubclassFolder.h"
#include <functional>

GLOBAL_NAMESPACE_BEGIN
NAMESPACE_MACHINE_LEARNING_BEGIN

namespace {
    static bool isSetEqual(const std::vector<int>& lhs, const std::vector<int>& rhs)
    {
        if (lhs.size()!=rhs.size()) return false;
        std::vector<int>::const_iterator liter = lhs.begin(), riter = rhs.begin();

        while (liter!=lhs.end() && riter!=rhs.end())
        {
            if (*liter != *riter)
                return false;
            liter++;
            riter++;
        }
        return true;
    }

    class SetCmp
    {
    public:
        SetCmp(const std::vector<int>& l) { lhs = &l; }

        bool operator() (const std::vector<int>& rhs)
        {
            return isSetEqual(*lhs, rhs);
        }
    private:
        const std::vector<int>* lhs;
    };
}

MLSubClassFolder::MLSubClassFolder()
{
}

MLSubClassFolder::~MLSubClassFolder()
{
}

int MLSubClassFolder::getSubClassSize() const
{
    return subClasses_.size();
}

void MLSubClassFolder::addSubClass(const std::vector<int>& subClass, int newAddedClass)
{
    std::vector<int> ordered = subClass;
    std::sort(ordered.begin(), ordered.end());
    if ( std::find_if(subClasses_.begin(), subClasses_.end(), SetCmp(ordered))
        != subClasses_.end() )
        return;

    subClasses_.push_back(subClass);
    newAddedClass_.push_back(newAddedClass);
}

const MLSubClassFolder::SubClass* MLSubClassFolder::getSubClass(int idx) const
{
    if (idx<0 || idx>getSubClassSize())
        return NULL;

    return &subClasses_[idx];
}

int MLSubClassFolder::getTheNewAddedClass(int idx) const
{
    if (idx<0 || idx>getSubClassSize())
        return -1;

    return newAddedClass_[idx];
}

NAMESPACE_MACHINE_LEARNING_END
GLOBAL_NAMESPACE_END

